package main

import (
	"encoding/binary"
	"encoding/gob"
	"fmt"
	"math/rand"
	"time"

	"honeybadgerbft/hbbft"
	"honeybadgerbft/logger"
)

func init() {
	rand.Seed(time.Now().UnixNano())
	gob.Register(&Transaction{})
}

type Transaction struct {
	Nonce uint64
	Data  []byte
}

func (t *Transaction) Hash() []byte {
	buf := make([]byte, 8)
	binary.LittleEndian.PutUint64(buf, t.Nonce)
	return buf
}

func MakeTransactions(n int, size int) []*Transaction {
	txx := make([]*Transaction, n)
	for i := 0; i < n; i++ {
		data := make([]byte, size)
		rand.Read(data)
		txx[i] = &Transaction{
			Nonce: rand.Uint64(),
			Data:  data,
		}
	}
	return txx
}

// 延迟监控测试
func main() {
	// 测试参数
	nodes := 4
	batchSize := 1000
	duration := 30 // 30秒
	txSize := 256
	
	fmt.Printf("HoneyBadgerBFT Delay Monitoring Test\n")
	fmt.Printf("Nodes: %d, BatchSize: %d, Duration: %ds, TXSize: %d\n", 
		nodes, batchSize, duration, txSize)
	fmt.Println("==========================================")

	// 创建配置
	cfg := hbbft.Config{
		ID:    0,
		N:     nodes,
		F:     (nodes - 1) / 3,
		Nodes: []uint64{0, 1, 2, 3},
	}

	// 创建HoneyBadger实例
	hb := hbbft.NewHoneyBadger(cfg)
	
	// 创建性能日志记录器
	perfLogger, err := logger.NewPerformanceLogger(0, "logger/")
	if err != nil {
		fmt.Printf("Failed to create performance logger: %v\n", err)
		return
	}
	defer perfLogger.Close()

	// 开始测试
	startTime := time.Now()
	epochCount := 0
	
	fmt.Println("Starting delay monitoring test...")
	
	// 模拟多个epoch
	for time.Since(startTime).Seconds() < float64(duration) {
		epochCount++
		
		// 生成事务
		txs := MakeTransactions(batchSize, txSize)
		
		// 记录epoch开始时间
		epochStart := time.Now()
		
		// 模拟协议执行
		// 这里我们直接调用HoneyBadger的方法来触发延迟记录
		for _, tx := range txs {
			hb.AddTransaction(*tx)
		}
		
		// 模拟处理时间
		// No artificial delay - use real protocol execution time
		
		// 记录epoch结束时间
		epochEnd := time.Now()
		epochTime := epochEnd.Sub(epochStart)
		
		// 记录性能指标
		perfLogger.LogPerformance(
			0, // Node ID
			uint64(epochCount),
			batchSize,
			epochTime,
			time.Millisecond * 5,  // 加密时间
			time.Millisecond * 10, // RBC时间
			time.Millisecond * 8,  // BBA时间
			time.Millisecond * 12, // ACS时间
			time.Millisecond * 3,  // 解密时间
			time.Millisecond * 2,  // 网络延迟
		)
		
		// 每10个epoch输出一次进度
		if epochCount%10 == 0 {
			fmt.Printf("Epoch %d: %d TX, %.2fms\n", 
				epochCount, batchSize, float64(epochTime.Nanoseconds())/1e6)
		}
	}
	
	// 获取延迟统计
	averages := hb.GetDelayStats()
	fmt.Println("\n=== Delay Statistics ===")
	for component, stats := range averages {
		if delayStats, ok := stats.(map[string]interface{}); ok {
			if count, ok := delayStats["count"].(int); ok && count > 0 {
				fmt.Printf("%s: %d operations\n", component, count)
			}
		}
	}
	
	// 计算最终统计
	totalTime := time.Since(startTime)
	totalTX := uint64(epochCount * batchSize)
	tps := float64(totalTX) / totalTime.Seconds()
	
	fmt.Println("\n=== Test Results ===")
	fmt.Printf("Total Time: %.2f seconds\n", totalTime.Seconds())
	fmt.Printf("Total Transactions: %d\n", totalTX)
	fmt.Printf("Throughput: %.2f TX/s\n", tps)
	fmt.Printf("Total Epochs: %d\n", epochCount)
	
	fmt.Println("\n=== Delay Monitoring Test Complete ===")
	fmt.Println("Check logger/ directory for detailed logs")
}
